/**
 * @description: utils
 * @date: 2020/12/23
 */

function Deferred() {
    var promiseObj = {};
    promiseObj.promise = new Promise((resolve, reject) => {
        promiseObj.resolve = resolve;
        promiseObj.reject = reject;
    })

    return promiseObj;
}

function _appendNode(node) {
    var defer = Deferred();

    node.onload = function (...args) {
        defer.resolve(...args);
        defer = node = node.onload = null;
    }

    node.onerror = function (...args) {
        defer.reject(...args);
        defer = node = node.onload = null;
    }

    document.head.appendChild(node);
    return defer.promise;
}

function _addAttr(node, attrs) {
    attrs = attrs || [];

    attrs.forEach(item => {
        node.setAttribute(item.key, item.value);
    })
}

function addStyle(url, attrs) {
    var node = document.createElement('link');
    node.rel = 'stylesheet';
    node.href = url;

    _addAttr(node, attrs);

    return _appendNode(node);
}

function addScript(url, attrs) {
    var node = document.createElement('script');
    node.type = 'text/javascript';
    node.src = url;
    node.async = true;

    _addAttr(node, attrs);

    return _appendNode(node);
}

/**
 * 添加外部资源
 * @param {'js'|'css'} type - js or css
 * @param {string} url
 * @returns {Promise<never>|Promise<unknown>}
 */
function addOutsideResource(type, url, attrs) {
    switch (type) {
        case 'js':
            return addScript(url, attrs);
        case 'css':
            return addStyle(url, attrs);
        default:
            return Promise.reject(new Error(`the ${type} is not available to 'js' or 'css'`))
    }
}
